package cn.itsource.basic.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;


/*登录检查拦截器:每次ajax请求都会走这个拦截器*/

@Component//通用注解
public class LoginInterceptor implements HandlerInterceptor {
    
    @Autowired
    private RedisTemplate redisTemplate;
    

    /*
    1.从请求头中获取token
    1.1没有获取到,响应 success:false message:noLogin---Json字符串
    1.2获取到 查询redis
    1.2.1查到,放行
    1.2.2未查到,响应success:false message:noLogin---Json字符串
    */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

//        1.从请求头中获取token
        String token = request.getHeader("U-TOKEN");

        //获取到,查询redis,在redis中查到,放行
        if (!StringUtils.isBlank(token)){
            Object tokenInRedis = redisTemplate.opsForValue().get(token);
            if (tokenInRedis != null){
                //不为空,登录状态延长30分钟
                redisTemplate.opsForValue().set(token,tokenInRedis,30, TimeUnit.MINUTES);
                return true;
            }
        }

        //除以上这种状态,其余情况都需要拦截
        PrintWriter writer = response.getWriter();//响应回前端需要声明字符编码 ↑32,33行
        writer.write("{\"success\":\"false\",\"message\":\"noLogin\"}");//写出一个Json字符串  {"success":"false","message":"noLogin"}
        writer.flush();
        writer.close();
        //不放行
        return false;
    }
}